<template>
  <div class="show-main">
    <el-scrollbar style="height:100%">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item prop="name">
              <el-input v-model="searchForm.name" clearable placeholder="请输入司机名称"></el-input>
            </el-form-item>
            <el-form-item prop="status">
              <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
                <el-option label="正常" value="1"></el-option>
                <el-option label="禁用" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click.stop="search">搜索</el-button>
              <el-button type="success" @click.stop="reload">刷新</el-button>
              <el-button type="warning" @click.stop="add">添加</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="table" border>
          <el-table-column prop="id" label="ID" width="70"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="account" label="账号"></el-table-column>
          <el-table-column prop="phone" label="电话" width="100"></el-table-column>
          <el-table-column prop="gender" label="性别" width="70">
            <template slot-scope="scope">
              {{scope.row.gender|genderName}}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="70">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.status == 1 ?'正常': '禁用'" placement="top" :enterable="false">
                <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" @change="changeStatus(scope.row)">
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="150">
            <template slot-scope="scope">
              {{scope.row.create_time|formatDate}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template slot-scope="scope">
              <el-dropdown trigger="click" @command="dropdownClick">
                <el-button type="primary">
                  操作<i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item :command="{type:'edit', id:scope.row.id}">编辑</el-dropdown-item>
                  <el-dropdown-item :command="{type:'del', id:scope.row.id}">删除</el-dropdown-item>
                  <el-dropdown-item :command="{type:'forcePwd', id:scope.row.id}">修改密码</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchForm.page"
            :page-sizes="[10,20,30,40]" :page-size="searchForm.limit" layout="total, sizes, prev, pager, next, jumper" :total="count">
          </el-pagination>
        </div>
      </el-card>
      <el-dialog title="编辑司机" :visible.sync="editVisible" :before-close="handleClose('editForm')" width="800px">
        <el-form ref="editForm" :model="editForm" label-width="80px" :rules="rules">
          <el-form-item label="真实姓名" prop="name">
            <el-input v-model="editForm.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input v-model="editForm.account" clearable></el-input>
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="editForm.phone" maxlength="11" show-word-limit clearable></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="editForm.gender">
              <el-radio :label="1" border>男</el-radio>
              <el-radio :label="2" border>女</el-radio>
              <el-radio :label="0" border>保密</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('editVisible', 'editForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('editVisible','editForm')" size="small">编 辑</el-button>
        </span>
      </el-dialog>
      <el-dialog title="添加司机" :visible.sync="addVisible" :before-close="handleClose('addForm')" width="500px">
        <el-form ref="addForm" :model="addForm" label-width="80px" :rules="rules">
          <el-form-item label="真实姓名" prop="name">
            <el-input v-model="addForm.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input v-model="addForm.account" clearable></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="pwd">
            <el-input v-model="addForm.pwd" show-password clearable></el-input>
          </el-form-item>
          <el-form-item label="密码确认" prop="repwd">
            <el-input v-model="addForm.repwd" show-password clearable></el-input>
          </el-form-item>
          <el-form-item label="电话号码" prop="phone">
            <el-input v-model="addForm.phone" maxlength="11" show-word-limit clearable></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="addForm.gender">
              <el-radio :label="1" border>男</el-radio>
              <el-radio :label="2" border>女</el-radio>
              <el-radio :label="0" border>保密</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('addVisible', 'addForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('addVisible','addForm')" size="small">添 加</el-button>
        </span>
      </el-dialog>
      <el-dialog title="修改密码" :visible.sync="forcePwdVisible" :before-close="handleClose('forcePwdForm')">
        <el-form ref="forcePwdForm" :model="forcePwdForm" label-width="80px" :rules="rules">
          <el-form-item label="密码" prop="pwd">
            <el-input v-model="forcePwdForm.pwd" show-password clearable></el-input>
          </el-form-item>
          <el-form-item label="密码确认" prop="checkpwd">
            <el-input v-model="forcePwdForm.checkpwd" show-password clearable></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('forcePwdVisible', 'forcePwdForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('forcePwdVisible','forcePwdForm')" size="small">确 定</el-button>
        </span>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>
<script>
import { getDriverList, getDriverOnly, addDriver, changeDriverStatus, editDriver, delDriver, forceDriverPwd } from '@/network/api.js'

export default {
  name: 'driver',
  data() {
    return {
      searchForm: {
        page: 1,
        limit: 10,
        name: '',
        status: ''
      },
      table: [],
      count: 0,
      editForm: {
        id: 0,
        name: '', // 名称
        gender: 1, // 性别 1：男 2：女 0 保密'
        phone: '', // 手机号
        account: '' // 用户名
      },
      // 添加表单
      addForm: {
        name: '', // 名称
        gender: 1, // 性别 1：男 2：女 0 保密'
        phone: '', // 手机号
        account: '', // 用户名
        pwd: '', // 密码
        repwd: '' // 再次密码
      },
      forcePwdForm: {
        id: 0,
        pwd: '', // 密码
        checkpwd: '' // 密码确认
      },
      orgInfo: [], // 机构列表
      editVisible: false, // 编辑
      addVisible: false, // 添加
      forcePwdVisible: false, // 修改密码
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      rules: {
        name: [
          { required: true, message: '名称必须', trigger: 'blur' },
          { min: 2, max: 10, message: '名称在 2 到 10 个字符', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '账号必须', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!/^[0-9a-zA-Z]{3,20}$/.test(value)) {
                callback(new Error('账号3到20位数字，大小写字母组成'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        pwd: [
          { required: true, message: '密码必须', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!/^[0-9a-zA-Z]{6,12}$/.test(value)) {
                callback(new Error('密码6到12位数字，大小写字母组成'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        repwd: [
          { required: true, message: '密码确认必须', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.addForm.pwd) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        checkpwd: [
          { required: true, message: '密码确认必须', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.forcePwdForm.pwd) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        phone: [
          { required: true, message: '手机号必须', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!/^1[3456789]\d{9}$/.test(value)) {
                callback(new Error('请输入正确的手机号!'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        gender: [{ required: true, message: '性别必须', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.search()
  },
  computed: {},
  methods: {
    reload() {
      this.$refs.searchForm.resetFields()
      this.searchForm.limit = 10
      this.searchForm.page = 1
      this.search()
    },
    // 每页条数变化
    handleSizeChange(val) {
      this.searchForm.limit = val
      this.search()
    },
    // 当前页变化
    handleCurrentChange(val) {
      this.searchForm.page = val
      this.search()
    },
    async search() {
      try {
        const rtn = await getDriverList(this.searchForm)
        this.table = rtn.list
        this.count = rtn.count
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 添加
    add() {
      this.addVisible = true
    },
    // 修改状态
    changeStatus(ev) {
      let msg = ''
      let oldStatus = ''
      switch (ev.status) {
        case 1:
          msg = '您确定要启用该司机吗?'
          oldStatus = 2
          break
        case 2:
          msg = '此操作将禁用该司机, 是否确定?'
          oldStatus = 1
          break
        default:
          return this.$message.error('不可用的操作')
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(async () => {
          try {
            await changeDriverStatus({ id: ev.id, status: ev.status })
          } catch (e) {
            ev.status = oldStatus
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          ev.status = oldStatus
          this.$message.warning('您已取消操作')
        })
    },
    // 下拉操作
    async dropdownClick(command) {
      switch (command.type) {
        case 'edit': // 编辑
          try {
            const rtn = await getDriverOnly({ id: command.id })
            this.editForm = rtn
            this.editVisible = true
          } catch (e) {
            this.$message.error(e.message)
          }
          break
        case 'del': // 删除
          this.$confirm('您确定要删除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              try {
                await delDriver({ id: command.id })
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
            })
            .catch(() => {
              this.$message.warning('您已取消操作')
            })
          break
        case 'forcePwd': // 修改密码
          this.forcePwdForm.id = command.id
          this.forcePwdVisible = true
          break
      }
    },
    // 关闭弹出前操作(不包括取消按钮)
    handleClose(formName) {
      return done => {
        this.$refs[formName].clearValidate()
        this.$refs[formName].resetFields()
        done()
      }
    },
    // 取消按钮
    close(visibleName, formName) {
      this.$refs[formName].clearValidate()
      this.$refs[formName].resetFields()
      this[visibleName] = false
    },
    send(visibleName, formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          switch (formName) {
            case 'editForm': // 编辑司机
              try {
                await editDriver(this.editForm)
                this.close(visibleName, formName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'addForm': // 添加司机
              try {
                await addDriver(this.addForm)
                this.close(visibleName, formName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'forcePwdForm': // 修改密码
              try {
                await forceDriverPwd(this.forcePwdForm)
                this.close(visibleName, formName)
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
          }
        } else {
          this.$message.error('请检查表单')
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/.el-tree-node {
  display: inline-block;
}
</style>
